// The payment page
// ================

define(['zepto', 'utils', 'wxpay', 'wxshare', 'sui'], function($, utils, wxpay, wxshare) {
  return {

    init: function(data) {
      
      // forbidden wx share
      wxshare.initShare(data.jsConfig, false)
      
      this.orderId = parseInt(data.orderId)
      this.orderType = data.orderType
      this.onWxBtnClick()
    },
    
    /**
     * Bind handler on clicking wx payment button
     */
    onWxBtnClick: function(orderId) {
      var that = this
      $('#wx-pay').on("click", function(e) {
        e.preventDefault()
        that.requestWxPay()
      }) 
    },

    /**
     * Request server to prepare WeChat payment data
     */
    requestWxPay: function() {
      $.showPreloader('正在提交支付数据')
      var that = this
      $.ajax({
        type: 'POST',
        url: __CTX__.root + '/wxpay/prepare',
        data: {
          'orderId': this.orderId,
          'currentUrl': location.href.split('#')[0]
        }
      }).done(function(response) {
        $.hidePreloader()
        utils.processResult(response, that.configWxPay.bind(that), function(result) {
          $.toast(result.message || '请求支付数据失败')
        })
      })
    },

    /**
     * Handle success WeChat pay, config WeChat JS SDK and invoke pay
     */
    configWxPay: function(result) {
      var that = this
          jsConfig = result.data.jsConfig,
          payConfig = result.data.payConfig

      wxpay.injectConfig(jsConfig, ['chooseWXPay'])
      wxpay.invokePay(payConfig, function(res) {
        $.toast('支付成功，正在为您跳转')
        setTimeout(function() {
          
          if(that.orderType == 'ONLINE') {
            // window.location.href = window.__CTX__.root + '/orders/' + that.orderId + "/payment-protocol"
            window.location.href = window.__CTX__.root + '/orders/' + that.orderId + "/complete2" 

          } else {
        	  window.location.href = window.__CTX__.root + '/orders/' + that.orderId + "/complete2" 
          }
          
        }, 1000)
      })
    }
  }
})